import 'moment/locale/zh-cn';

import { message } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React, { PureComponent } from 'react';

import MarketChange from './marketChange/marketChange'; // 市场异动
import TradeDetail from './tradeDetail/tradeDetail'; // 交易明细
import TradeReplay from './tradeReplay/tradeReplay'; // 交易复盘
import TradeStatistics from './tradeStatistics/tradeStatistics'; // 交易统计

import { NoQueryC, DATA_ENTRY, AdvancedSearch, FirstHeaderC } from '../../../components';

class TradeAnalysisNew extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      beginDate: '', // 传入各组件的时间
      endDate: '', // 传入各组件的结束时间
      secuBeginDate: '', // （YYYYMMDD）证券代码入参
      secuEndDate: '', // （YYYYMMDD）证券代码入参
      portfolioCodeList: undefined, // 传入各组件的产品code
      isShow: false, // 是否展示详细信息
      isReplayShow: false, // 是否展示交易复盘
      searchObj: undefined,
      codeKey: undefined,
    };
  }

  componentDidMount() {
    this.getStorageData();
  }

  componentDidUpdate() {
    // 用户试图跳转过来
    if (sessionStorage.getItem('tradeManageRecord')) {
      const item = JSON.parse(sessionStorage.getItem('tradeManageRecord'));
      sessionStorage.removeItem('tradeManageRecord');
      // 【用户视图】交易明细列表点击跳转，时间区间应默认展示为前一天
      const Yesterday = moment().subtract(1, 'day');
      this.myDate.setDate([Yesterday, Yesterday]);
      this.timerId = setInterval(() => {
        if (this.product?.state?.dataSource.length > 0) {
          clearInterval(this.timerId);

          const productData = this.product?.state?.dataSource.find((v) => v.code === item.productCode);
          const productId = productData.value;
          this.product.props.form.setFieldsValue({
            product: [productId],
          });
          // 拼changePortfolio的参数
          const productCodeE = {
            info: [
              {
                code: item.productCode ?? '',
                mame: item.productCode ?? '',
                title: `${item.productCode} - ${item.productName}`,
                value: productId,
                id: productId,
              },
            ],
          };
          // 调用searchData的参数
          const searchE = {
            product: [item.productId],
            beginDate: Yesterday,
            endDate: Yesterday,
          };
          this.changePortfolio(productCodeE, true, searchE);
        }
      }, 100);
      // setTimeout(() => {
      //   // 获取产品列表
      //   const productData = this.product?.state?.dataSource.find(v => v.code === item.productCode)
      //   const productId = productData.value
      //   this.product.props.form.setFieldsValue({
      //     product: [productId],
      //   })
      //   // 拼changePortfolio的参数
      //   const productCodeE = {
      //     info: [{
      //       code: item.productCode ?? '',
      //       mame: item.productCode ?? '',
      //       title: item.productCode + ' - ' + item.productName,
      //       value: productId,
      //       id: productId,
      //     }],
      //   }
      //   //调用searchData的参数
      //   const searchE = {
      //     product: [item.productId],
      //     beginDate: moment().subtract(1, 'months').subtract(1, 'day'),
      //     endDate: moment().subtract(1, 'day'),
      //   }
      //   this.changePortfolio(productCodeE, true, searchE);
      // }, 1000)
    }
  }

  /**
   * 产品改变
   * @param e  // 产品改变的参数
   * @param { boolean } isUseView  // 是否是用户视图跳转来的
   * @param {{ product, beginDate, endDate }}searchE // 调用searchData的参数
   */
  changePortfolio = (e, isUseView, searchE) => {
    if (e) {
      const tempArr = [];
      e.info.forEach((item) => {
        tempArr.push(item.code);
      });
      this.setState(
        {
          portfolioCodeList: tempArr,
        },
        () => {
          if (isUseView) {
            this.searchData(searchE);
          }
        },
      );
    } else {
      this.setState(
        {
          portfolioCodeList: undefined,
        },
        () => {
          if (isUseView) {
            this.searchData(searchE);
          }
        },
      );
    }
  };

  // 搜索点击事件
  searchData = (e) => {
    if (e.product && e.product.length) {
      if (e.endDate && e.beginDate) {
        const tempObj = {};
        tempObj.portfolioCodeList = this.state.portfolioCodeList;
        tempObj.beginDate = e.beginDate.format('YYYY-MM-DD');
        tempObj.endDate = e.endDate.format('YYYY-MM-DD');
        this.setState(
          {
            portfolioCodeList: tempObj.portfolioCodeList,
            beginDate: e.beginDate.format('YYYY-MM-DD'),
            endDate: e.endDate.format('YYYY-MM-DD'),
            secuBeginDate: e.beginDate.format('YYYYMMDD'),
            secuEndDate: e.endDate.format('YYYYMMDD'),
            searchObj: tempObj,
            isShow: true, // 判断是否展示页面的条件
            isReplayShow: false,
          },
          () => {
            this.setState({
              isReplayShow: true,
            });
          },
        );
      } else {
        message.warning('请填写完整的查询条件');
        this.setState({
          beginDate: undefined,
          endDate: undefined,
        });
      }
    } else {
      message.warning('请选择产品');
    }
  };

  // 从组合概览跳转   拿到sessionStorage中的查询条件
  getStorageData = () => {
    const overviewData = JSON.parse(sessionStorage.getItem('searchObj'));
    sessionStorage.removeItem('searchObj');
    if (overviewData) {
      const { portfolioCode, portfolioName, beginDate, endDate, codeKey } = overviewData;
      this.setState(
        {
          codeKey,
          portfolioCode,
          beginDate,
          endDate,
          portfolioName,
          portfolioCodeList: [portfolioCode],
        },
        () => {
          const { portfolioCode, beginDate, endDate, portfolioName } = this.state;
          // 拼changePortfolio的参数
          const productCodeE = {
            info: [
              {
                code: portfolioCode ?? '',
                mame: portfolioName ?? '',
                title: `${portfolioCode} - ${portfolioName}`,
                value: portfolioCode,
                id: portfolioCode,
              },
            ],
          };
          // 调用searchData的参数
          const searchE = {
            product: [portfolioCode],
            beginDate: moment(beginDate),
            endDate: moment(endDate),
          };
          this.searchData(searchE);
          this.changePortfolio(productCodeE, false, searchE);
        },
      );
    }
  };

  render() {
    const { isShow, isReplayShow, portfolioCode, beginDate, endDate, codeKey } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'product',
          title: '产品',
          type: DATA_ENTRY.PRODUCTLIST,
          multiple: true,
          maxTagCount: 0,
          dataType: 2,
          onRef: (ref) => (this.product = ref),
          isQueryDetail: false, // 不用查询详情
          onChange: (e) => this.changePortfolio(e),
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE', 'VALUATION_BOOKKEEPING_MODEL'],
          initialValue: codeKey || [],
        },
        {
          dataIndex: ['beginDate', 'endDate'],
          title: '日期区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: beginDate && endDate ? [moment(beginDate), moment(endDate)] : [moment().subtract(1, 'months').subtract(1, 'day'), moment().subtract(1, 'day')],
          hasDataED: moment().subtract(1, 'day'),
          onRef: (ref) => {
            this.myDate = ref;
          },
        },
      ],
      onQuery: (e) => {
        this.searchData(e);
      },
      onClear: () => {
        // 日期重置方法
        this.myDate.reset();
        this.setState({
          codeKey: '',
        });
      },
    };
    return (
      <div style={{ height: '100%' }}>
        <div style={{ marginBottom: '20px' }}>
          {/* eslint-disable-next-line react/jsx-props-no-spreading */}
          <AdvancedSearch {...searchProps} />
        </div>
        {isShow ? (
          <>
            <div style={{ marginBottom: '20px' }}>
              <FirstHeaderC title='交易统计' />
              <TradeStatistics searchObj={this.state.searchObj} />
            </div>
            <div style={{ marginBottom: '20px' }}>
              <FirstHeaderC title='市场异动' />
              <MarketChange searchObj={this.state.searchObj} />
            </div>
            {isReplayShow ? (
              <div style={{ marginBottom: '20px' }}>
                <TradeReplay searchObj={this.state.searchObj} secuBeginDate={this.state.secuBeginDate} secuEndDate={this.state.secuEndDate} />
              </div>
            ) : null}

            <div style={{ marginBottom: '20px' }}>
              <FirstHeaderC title='交易明细' />
              <TradeDetail searchObj={this.state.searchObj} />
            </div>
          </>
        ) : (
          <NoQueryC />
        )}
      </div>
    );
  }
}
export default connect(({ TradeAnalysisNewM, loading }) => ({
  TradeAnalysisNewM,
  loading,
}))(TradeAnalysisNew);
